<template>
    <div class="edu-page-warp">
        <div class="edu-page-title">
            <span
                v-for="item in tabs"
                :key="item.name"
                @click="changeTab(item)"
                :class="{active: activeTab == item.name}"
            >{{item.label}}</span>
        </div>
        <div style="margin-top:10px" class="bg-white pd-20px">
            <FieldAuthority
                :show-edit="functions['edit_field_auth']"
                :table-data="tableData"
                :operates-data="operatesData"
                v-on:save-data="saveData"
                v-on:search="search"
                v-on:download="download"
                v-on:upload="upload"
                ref="fieldAuthority"
            />
            <div class="edu-pagination">
                <div class="float-right">
                    <el-pagination
                        :current-page="pageNum_"
                        :page-sizes="[20,50,100,500,1000]"
                        :page-size="pageSize_"
                        :total="total_"
                        layout="total, sizes, prev, pager, next, jumper"
                        style="float: right;margin:10px 60px 0 0;"
                        @size-change="onPageSizeChange"
                        @current-change="onCurrentPageChange"
                    />
                </div>
            </div>
        </div>
        <el-dialog :title="$t('message.prompt')" width="450px" :visible.sync="showDialog">
            <div>您的当前操作尚未保存，是否确认切换页签？</div>
            <div class="float-right" style="margin:25px 0 0 0">
                <el-button @click="showDialog=false">{{$t("message.cancel")}}</el-button>
                <el-button @click="saveData(true)" type="primary">保存并切换</el-button>
                <el-button @click="confirmOpr" type="primary">{{$t("message.confirm")}}</el-button>
            </div>
            <div style="clear:both"></div>
        </el-dialog>
        <edu-dialog
            title="学生信息字段权限导入"
            width="40%"
            ref="uploadDialog"
            @close="clearFiles"
            @confirm="uploadFile"
        >
            <div style="height:100px">
                <el-form label-width="85px">
                    <el-form-item>
                        <el-upload
                            ref="upload"
                            :data="{}"
                            :on-success="uploadDone"
                            :on-error="onError"
                            :auto-upload="false"
                            :multiple="false"
                            :on-change="(file, fileList)=>{this.fileList = fileList}"
                            :limit="1"
                            accept=".xlsx"
                            action="api/studentservice/configOptions/importStuFieldConfig"
                            :before-upload="beforeAvatarUpload"
                        >
                            <el-button
                                slot="trigger"
                                size="small"
                                type="primary"
                            >{{$t('label.selectFile')}}</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传.xlsx文件</div>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </div>
        </edu-dialog>
    </div>
</template>
<script>
import { FieldAuthority } from "common/src/views/tools/";
import {
    getFieldsByTableName,
    getOperatesOfField,
    saveOperatesOfField,
    getConfigInfo,
    downloadTemplate
} from "common/src/api/studentinfo";
export default {
    name: "StudentRollAuthority",
    components: {
        FieldAuthority
    },
    mounted() {
        let _that = this;
        getOperatesOfField()
            .then(res => {
                this.operatesData = res.data;
                return res.data;
            })
            .then(_ => {
                _that.initPageData();
            })
            .catch(error => {
                _that.$message({
                    type: "error",
                    message: "页面加载失败."
                });
                console.log(error);
            });
    },
    data() {
        return {
            tabs: [
                {
                    label: this.$t("student.baseInfo"),
                    name:
                        "student_basic_information_t,student_contact_information_t"
                },
                {
                    label: this.$t("student.status"),
                    name:
                        "student_status_information_t,student_admission_information_t"
                },
                {
                    label: this.$t("student.educationalBackground"),
                    name: "student_educational_backgroud_t"
                },
                {
                    label: this.$t("student.workExperience"),
                    name: "student_work_experience_t"
                },
                {
                    label: this.$t("student.jointTraining"),
                    name: "student_joint_training_t"
                },
                {
                    label: this.$t("student.certificateInfo"),
                    name: "student_paperwork_t"
                },
                {
                    label: this.$t("student.contacts"),
                    name: "student_family_members_t"
                },
                {
                    label: this.$t("student.dormitory"),
                    name: "student_dormitory_t"
                },
                {
                    label: this.$t("student.other"),
                    name: "student_other_infomation_t,student_passport_t"
                }
            ],
            activeTab:
                "student_basic_information_t,student_contact_information_t",
            fieldData: [],
            operatesData: [],
            tableData: [],

            functions: {},
            showDialog: false,
            item: null,
            pageSize_: 20,
            pageNum_: 1,
            total_: 100,
            condition: null,
            fileList: []
        };
    },
    created() {
        this.$store.getters.getFuncUnderPage(this.$route.path).then(funcs => {
            this.functions = funcs;
        });
    },
    methods: {
        saveData(isToggle = false) {
            const data = {
                infoConfigList: this.tableData.map((item, i, arr) => {
                    return {
                        dictionaryId: item[1].id,
                        configurationIdList: item
                            .filter((ele, j) => {
                                return j > 1 && ele.name;
                            })
                            .map((l, k) => {
                                return l.id;
                            })
                    };
                })
            };
            if (!data) throw "数据异常";
            saveOperatesOfField(data)
                .then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: "success",
                            message: this.$t("message.saveSuccess")
                        });
                        if (isToggle) {
                            this.initPage();
                            this.showDialog = false;
                            this.activeTab = this.item.name;
                        } else {
                            this.tableData.forEach(row => {
                                row.forEach(col => {
                                    col.status = undefined;
                                });
                            });
                        }
                    } else "操作失败";
                })
                .catch(error => {
                    this.$message({
                        type: "error",
                        message: error
                    });
                });
        },
        initPageData(isFirstPage = false) {
            if (!this.operatesData) return;
            if (isFirstPage) {
                this.pageNum_ = 1;
            }
            let query = "tableName=" + this.activeTab;
            query += "&pageNum_=" + this.pageNum_;
            query += "&pageSize_=" + this.pageSize_;
            let keyword = this.$refs.fieldAuthority.getFilterText();
            if (keyword != null) {
                query += "&keyWord=" + encodeURI(keyword);
            }
            let _that = this;
            getFieldsByTableName(query)
                .then(res => {
                    if (res.code == 200) {
                        _that.fieldData = res.data.list;
                        this.total_ = res.data.total_;
                        return res.data.list;
                    } else throw res.code;
                })
                .then(fields => {
                    getConfigInfo(query).then(res => {
                        if (res.code == 200) {
                            _that.transData(fields, res.data);
                        } else throw res.code;
                    });
                })
                .catch(error => {
                    _that.$message({
                        type: "error",
                        message: "页面加载失败"
                    });
                });
        },
        transData(fields, columnData) {
            let _that = this;
            this.tableData = fields.map((item, i) => {
                let rowId = item.id;
                let row = [
                    {
                        id: rowId,
                        name: this.pageSize_ * (this.pageNum_ - 1) + i + 1
                    },
                    item
                ]; //默认前两列序号与字段列
                return row.concat(getRow(rowId, columnData));
            });
            function getRow(rowId, columnData) {
                return _that.operatesData.map(item => {
                    return columnData.some(col => {
                        return (
                            col.dictionaryId == rowId &&
                            col.configurationId == item.id
                        );
                    })
                        ? { id: item.id, name: true }
                        : { id: item.id, name: false };
                });
            }
        },
        changeTab(item) {
            if (this.activeTab !== item.name) {
                //检查是否存在改变
                let changed = false;
                this.tableData.forEach(row => {
                    row.forEach(col => {
                        if (col.status) {
                            changed = true;
                        }
                    });
                });
                if (changed) {
                    this.item = item;
                    this.showDialog = true;
                } else {
                    this.initPage();
                    this.activeTab = item.name;
                }
            }
        },
        confirmOpr() {
            this.initPage();
            this.showDialog = false;
            this.activeTab = this.item.name;
        },
        onPageSizeChange(value) {
            this.pageSize_ = value;
            this.initPageData();
        },
        onCurrentPageChange(value) {
            this.pageNum_ = value;
            this.initPageData();
        },
        initPage() {
            this.pageNum_ = 1;
            this.pageSize_ = 20;
            this.total_ = 0;
            this.$refs.fieldAuthority.clearFilterText();
        },
        search() {
            this.initPageData(true);
        },
        download() {
            window.open(downloadTemplate());
        },
        upload() {
            this.$refs.uploadDialog.open();
        },
        clearFiles() {
            this.$refs.upload.clearFiles();
            this.fileList = [];
        },
        uploadFile() {
            if (this.fileList.length == 0) {
                this.$message({
                    type: "warning",
                    message: "请选择要上传的文件"
                });
                return;
            }
            this.$refs.upload.submit();
        },
        uploadDone(res, file, fileList) {
            if (res.code == 200) {
                this.$message({
                    type: "success",
                    message: this.$t("common.tips.uploadSuccess")
                });
                this.$refs.uploadDialog.close();
                this.initPageData(true);
            } else {
                if (res.data && res.data.length > 0) {
                    let msg = "";
                    res.data.forEach(err => {
                        msg += "<div style='margin:5px 0'>" + err + "</div>";
                    });
                    this.$message({
                        duration: 5000,
                        type: "error",
                        dangerouslyUseHTMLString: true,
                        message: msg
                    });
                } else {
                    this.$message({
                        type: "error",
                        message: "错误码:" + res.code
                    });
                }
                this.clearFiles();
            }
        },
        onError(err, file, fileList) {
            let msg = JSON.parse(err.message);
            this.$message({
                type: "error",
                message: msg.message
            });
        },
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 10;
            if (!isLt2M) {
                this.$message.error("上传文件大小不能超过 10MB!");
                this.clearFiles();
                return false;
            }
            const types = [
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            ];
            if (!types.includes(file.type)) {
                this.$message.error("上传文件格式必须是.xlsx");
                this.clearFiles();
                return false;
            }
        }
    },
    watch: {
        activeTab: function(_old, _new) {
            this.initPageData(true);
        }
    }
};
</script>
<style lang="scss" scope>
.edu-page-title {
    & > span {
        cursor: pointer;
        display: inline-block;
        padding: 0 10px;
        color: #4c5c70;
        font-size: 16px;
    }
    & > span.active {
        color: #409eff;
    }
}
</style>
